#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#include <errno.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include "listenlib.c"

// #define PORT 8080
#define BUFFER_SIZE 1024 // 102400 =100 KB


int is_https_request(const char *buffer) {
    // 判断是否是 HTTPS 请求
    return strstr(buffer, "CONNECT") != NULL;
}

// Http的监听
int listen_http(int client_socket, char* buffer) {

    // 获取域名
    char buffer2[BUFFER_SIZE];
    strcpy(buffer2, buffer);
    // printf("HTTP Request 111:: socket= %d  buffer = %s\n", client_socket, buffer);
    char domain[256];  // 假设域名不超过 255 个字符
    char *method = strtok(buffer2, " ");
    char *url = strtok(NULL, " ");
    extractDomain(url, domain);
    // printf("HTTP Request 222:: %s \n", buffer);   
    

    // 创建套接字连接目标服务器
    int http_port = 80;
    if( strncmp(domain, "docker.api.local", 16) == 0 ){
        http_port = 88;
    }

    // printf("my_listen ... host = %s && url= %d \n", domain, client_socket);
    int target_socket = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in target_addr;
    target_addr.sin_family = AF_INET;
    target_addr.sin_addr.s_addr = INADDR_ANY;
    target_addr.sin_port = htons(http_port);
    int ir = inet_pton(AF_INET, domain, &target_addr.sin_addr);

    // printf("my_listen 111 == %d \n", ir);
    int sock_fd = -1;
    // sock_fd = socket_connect(target_host, target_port, 5);
    sock_fd = connect(target_socket, (struct sockaddr*)&target_addr, sizeof(target_addr));
    if (sock_fd < 0) {
        printf("Error connecting to target server - %d \n", sock_fd);
        close(client_socket);
        exit(EXIT_FAILURE);
    }

     // 接收请求并打印内容
    ssize_t buffer_len = 1;
    // read(client_socket, buffer, sizeof(buffer) - 1)
    ssize_t send_res = -1;
    while ( buffer_len > 0) {
        printf("Received target_socket111::: %d \n", target_socket);


        // 往目标服务器发送数据
        size_t bytes_sent = 0;
        size_t total_bytes = strlen(buffer);
        while (bytes_sent < total_bytes) {
            ssize_t result = send(target_socket, buffer, total_bytes - bytes_sent, 0);
            if (result == -1) {
                perror("Error sending data");
                close(client_socket);
                close(target_socket);
                exit(EXIT_FAILURE);
            } else {
                bytes_sent += result;
            }
        }

        if ( bytes_sent < 0 ){
            perror("Send failed");
            printf("Get error :%s \n", strerror(errno));
        }

        // 从目标服务器读取响应
        char target_buffer[BUFFER_SIZE];
        ssize_t bytes_received = recv(target_socket, target_buffer, sizeof(target_buffer), 0);
        if ( bytes_received < 0 ){
            perror("bytes_received failed");
            char* response = "HTTP/1.1 200 OK\r\nContent-Length: 16\r\n\r\n接收的数据为空!";
            send_res = send(client_socket, response, strlen(response), 0);
        } else {
            send_res = send(client_socket, target_buffer, bytes_received, 0);
        }

        if ( send_res > 0 ){
            printf("Send Client Success socket::: client_socket =%d, target_socket=%d \n", client_socket, target_socket);
            break;
        }

        // printf("get response 111 send = %zd ;; received = %zd buffer = %s... \n", bytes_received, send_res, buffer);
        // free(get_buffer);

        // buffer_len = read(client_socket, buffer, sizeof(buffer) - 1);
        buffer_len = recv(client_socket, buffer, sizeof(buffer), 0);
    }

    // 关闭套接字
    printf("my_listen 555 \n");
    close(client_socket);
    close(target_socket);
    return 0;
}
